/*
 * Copyright (C) 2014 luke.
 * 
 * This file is part of Silvie.
 * 
 * Silvie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Silvie is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Silvie.  If not, see <http://www.gnu.org/licenses/>.
 */

package utils;

import java.awt.Canvas;
import java.awt.Point;
import java.awt.ScrollPane;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

/**
 * Utility class allowing the user to scroll a Canvas contained in a ScrollPane
 * by dragging the Canvas around with the mouse.
 * 
 * @author luke
 */
public class CanvasDrag {
	private ScrollPane scrollPane;
	private Canvas canvas;
	private Point origin;

	/**
	 * CanvasDrag constructor.
	 * 
	 * @param scrollPane the ScrollPane to scroll
	 * @param canvas the Canvas to be dragged
	 */
	public CanvasDrag(ScrollPane scrollPane, Canvas canvas) {
		this.scrollPane = scrollPane;
		this.canvas = canvas;
		this.origin = null;
		addListeners();
	}

	/**
	 * Sets the appropriate mouse listeners for dragging the Canvas in the
	 * ScrollPane.
	 */
	private void addListeners() {
		this.canvas.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				CanvasDrag.this.origin = e.getPoint();
			}
		});
		this.canvas.addMouseMotionListener(new MouseMotionAdapter() {
			@Override
			public void mouseDragged(MouseEvent e) {
				if (CanvasDrag.this.origin != null) {
					Point destination = e.getPoint();
					int dx = CanvasDrag.this.origin.x - destination.x;
					int dy = CanvasDrag.this.origin.y - destination.y;
					Point scrollPosition = CanvasDrag.this.scrollPane.getScrollPosition();
					Point scrollToPosition = new Point(scrollPosition.x, scrollPosition.y);
					if (scrollPosition.x + dx > 0) {
						scrollToPosition.x += dx;
					} else {
						scrollToPosition.x = 0;
					}
					if (scrollPosition.y + dy > 0) {
						scrollToPosition.y += dy;
					} else {
						scrollToPosition.y = 0;
					}
					CanvasDrag.this.scrollPane.setScrollPosition(scrollToPosition);
				}
			}
		});
	}
}
